package com.eco.fanliapp.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.eco.fanliapp.common.response.ServerResponse;
import com.eco.fanliapp.dao.*;
import com.eco.fanliapp.entity.GoodsFreeIntegral;
import com.eco.fanliapp.entity.GoodsIdSetup;
import com.eco.fanliapp.entity.SyUserIntegral;
import com.eco.fanliapp.entity.SyUserIntegralRecord;
import com.eco.fanliapp.service.ISyUserIntegralService;
import com.eco.fanliapp.service.ITaoBaoService;
import com.eco.fanliapp.service.RedisLockService;
import com.eco.fanliapp.vo.OrderIntegralCountVo;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author jobob
 * @since 2019-12-24
 */
@Service
public class SyUserIntegralServiceImpl extends ServiceImpl<SyUserIntegralMapper, SyUserIntegral> implements ISyUserIntegralService {
    @Autowired
    private SyUserIntegralMapper syUserIntegralMapper;
    @Autowired
    private RedisLockService redisLockService;
    @Autowired
    private AppOrderDetailMapper appOrderDetailMapper;
    @Autowired
    private SyUserIntegralRecordMapper syUserIntegralRecordMapper;
    @Autowired
    private GoodsIdSetupMapper goodsIdSetupMapper;
    @Autowired
    private GoodsFreeIntegralMapper goodsFreeIntegralMapper;
    @Autowired
    private ITaoBaoService taoBaoService;


    /**
     * 积分查询
     *
     * @param userId
     * @return
     */
    @Override
    public ServerResponse integralQuery(Long userId) {
        Integer integralNum = syUserIntegralMapper.integralQuery(userId);
        if (integralNum == null || integralNum == 0) {
            return ServerResponse.createBySuccess("积分查询", 0);
        }
        return ServerResponse.createBySuccess("积分查询", integralNum);
    }

    /**
     * 订单兑换积分
     *
     * @param userId
     * @param orderId
     * @return
     */
    @Override
    public ServerResponse integralExchange(Long userId, Long orderId) {
        if (orderId == null || orderId.toString().isEmpty()) {
            return ServerResponse.createByErrorMessage("订单号有误，请输入正确的订单号");//
        }

        if (orderId.toString().length() != 18) {
            return ServerResponse.createByErrorMessage("订单号有误，请输入正确的订单号");//
        }
        String strKey = "app_user_integral_echange_" + orderId;
        //redis锁-时间
        long startTimes = System.currentTimeMillis() + 1000 * 60;

        //获取锁
        if (!redisLockService.lock(strKey, startTimes + "")) {
            return ServerResponse.createByErrorMessage("已重复提交，请输入正确的订单号");//
        }

        OrderIntegralCountVo orderIntegralCountVo = appOrderDetailMapper.selectDetailByTradeIdAndUserId(orderId);
        if (orderIntegralCountVo == null || orderIntegralCountVo.getCountNum() <= 0) {
            return ServerResponse.createByErrorMessage("无效订单号，请输入正确的订单号");//
        }
        if (orderIntegralCountVo.getCountNum() == 1 && orderIntegralCountVo.getGoodsId() != 0) {
            //goodsId 在 goods_id_integral 表中做对比
            Integer number = goodsIdSetupMapper.selectByGoodsIdNum(orderIntegralCountVo.getGoodsId());
            if (number >= 1) {
                return ServerResponse.createByErrorMessage("福利商品无法兑换积分");
            }
        }
        Integer integralNumber = syUserIntegralRecordMapper.selectIntegralRecordByOrderId(orderId);
        if (integralNumber > 0) {
            return ServerResponse.createByErrorMessage("此订单已兑换，请输入正确的订单号");//
        }

        //查询条件，根据用户id查询用户积分
        QueryWrapper<SyUserIntegral> queryWrapper = new QueryWrapper();
        queryWrapper.eq("user_id", userId);
        SyUserIntegral syUserIntegral = syUserIntegralMapper.selectOne(queryWrapper);
        Integer status = 0;
        if (syUserIntegral == null) {
            SyUserIntegral syUserIntegral_one = new SyUserIntegral();
            syUserIntegral_one.setUserId(userId);
            syUserIntegral_one.setIntegralBalanceAmount(1);
            syUserIntegral_one.setIntegralFreezeAmount(0);
            syUserIntegral_one.setIntegralTotalAmount(1);
            syUserIntegral_one.setCreateTime(new Date());
            status = syUserIntegralMapper.insert(syUserIntegral_one);
        } else {
            status = syUserIntegralMapper.updateBalanceByUserId(userId);
        }
        //积分修改成功，插入记录
        Integer recordStatus = 0;
        if (status > 0) {
            QueryWrapper<SyUserIntegral> queryWrapper2 = new QueryWrapper();
            queryWrapper2.eq("user_id", userId);
            SyUserIntegral syUserIntegral2 = syUserIntegralMapper.selectOne(queryWrapper2);
            SyUserIntegralRecord syUserIntegralRecord = new SyUserIntegralRecord();
            syUserIntegralRecord.setUserId(userId);
            syUserIntegralRecord.setOperBindingOrder(orderId);
            syUserIntegralRecord.setIntegralOpertAmount(1);
            syUserIntegralRecord.setIntegralOperBeforeAmount(syUserIntegral == null ? 1 : syUserIntegral.getIntegralBalanceAmount());
            syUserIntegralRecord.setIntegralOperAfterAmount(syUserIntegral2.getIntegralBalanceAmount());
            syUserIntegralRecord.setOperReason("1");
            syUserIntegralRecord.setCreateTime(new Date());

            recordStatus = syUserIntegralRecordMapper.insert(syUserIntegralRecord);
        } else {
            return ServerResponse.createByErrorMessage("请微信联系鸭鸭");//增加积分失败
        }
        if (recordStatus > 0) {
            return ServerResponse.createBySuccess("积分+1");//记录添加成功
        } else {
            return ServerResponse.createByErrorMessage("请微信联系鸭鸭");//记录添加失败
        }
    }

    /**
     * 积分兑换商品
     *
     * @param userId
     * @param goodsId
     * @return
     */
    @Override
    public ServerResponse integralExchangeGoods(Long userId, Long goodsId) {
        String strKey = "app_user_integral_echange_goods" + userId + "_" + goodsId;
        //redis锁-时间
        long startTimes = System.currentTimeMillis() + 1000 * 60;

        //获取锁
        if (!redisLockService.lock(strKey, startTimes + "")) {
            return ServerResponse.createByErrorMessage("操作频繁，请稍后再试");//操作频繁
        }
        //1判断是否兑换过
        QueryWrapper<SyUserIntegralRecord> queryWrapper_one = new QueryWrapper();
        queryWrapper_one.eq("user_id", userId);
        queryWrapper_one.eq("oper_binding_goods_id", goodsId);
        SyUserIntegralRecord integralRecord = syUserIntegralRecordMapper.selectOne(queryWrapper_one);
        if (integralRecord != null) {
            return ServerResponse.createByErrorMessage("此商品已兑换，看一下其他商品吧");//已兑换
        }
        //2判断积分是否满足
        GoodsFreeIntegral goodsFreeIntegral = goodsFreeIntegralMapper.selectByGoodsId(goodsId);
        if (goodsFreeIntegral != null) {
            Integer integralNum = syUserIntegralMapper.integralQuery(userId);
            if (integralNum == null || integralNum < goodsFreeIntegral.getIntegralNumber()) {
                return ServerResponse.createByErrorMessage("积分不足，看一下其他商品吧");//积分不够
            }
            ServerResponse response = taoBaoService.getPrivilegeGoodsFreeItemURL(goodsId.toString(), userId, 26, "2",null);
            if (response.getStatus() == 200) {
                //3积分冻结
                Integer status = syUserIntegralMapper.updateBalanceFreezeByUserId(userId, goodsFreeIntegral.getIntegralNumber());
                if (status > 0) {
                    //4插入兑换记录
                    QueryWrapper<SyUserIntegral> queryWrapper = new QueryWrapper();
                    queryWrapper.eq("user_id", userId);
                    SyUserIntegral syUserIntegral = syUserIntegralMapper.selectOne(queryWrapper);
                    SyUserIntegralRecord syUserIntegralRecord = new SyUserIntegralRecord();
                    syUserIntegralRecord.setUserId(userId);
                    syUserIntegralRecord.setItemshorttitle(goodsFreeIntegral.getGoodsTitle());
                    syUserIntegralRecord.setOperBindingGoodsId(goodsId.toString());
                    syUserIntegralRecord.setIntegralOpertAmount(goodsFreeIntegral.getIntegralNumber());
                    syUserIntegralRecord.setIntegralOperBeforeAmount(integralNum == null ? 0 : integralNum);
                    syUserIntegralRecord.setIntegralOperAfterAmount(syUserIntegral.getIntegralBalanceAmount());
                    syUserIntegralRecord.setOperReason("0");
                    syUserIntegralRecord.setCreateTime(new Date());
                    int recordStatus = syUserIntegralRecordMapper.insert(syUserIntegralRecord);
                    if (recordStatus > 0) {
                        return ServerResponse.createBySuccess("兑换成功",response.getData());//记录添加成功
                    } else {
                        return ServerResponse.createByErrorMessage("兑换失败");//记录添加失败
                    }
                }
            }
        }
        return ServerResponse.createByErrorMessage("兑换失败");
    }

    /**
     * 积分详情
     *
     * @param userId
     * @param type
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Override
    public ServerResponse integralList(Long userId, Integer type, Integer pageNum, Integer pageSize) {
        Integer star = (pageNum - 1) * pageSize;
        Integer end = pageNum * pageSize;
        List<SyUserIntegralRecord> list = syUserIntegralRecordMapper.selectIntegralRecordList(userId, type, star, end);
        if (list == null || list.size() <= 0) {
            return ServerResponse.createBySuccessCodeMessage(201, "暂无数据");//数据为空
        }
        return ServerResponse.createBySuccess(list);//记录添加成功;
    }

    /**
     * 积分商品列表
     *
     * @param userId
     * @param pageNum
     * @param pageSie
     * @return
     */
    @Override
    public ServerResponse integralGoodsList(Long userId, Integer pageNum, Integer pageSie) {
        PageHelper.startPage(pageNum, pageSie);
        List<GoodsFreeIntegral> goodsFreeIntegralList = goodsFreeIntegralMapper.selectByUserId(userId);
        return ServerResponse.createBySuccess("查询成功", new PageInfo(goodsFreeIntegralList));
    }
}
